#!/bin/bash
################################################################################
#  Copyright (C) 2015-2018 IQIYI All rights reserved.
# 
#  Author     : 王海斌
#  E-mail     : wanghaibin@qiyi.com
#  Version    :
#  Date       : Fri 30 Nov 2018 11:06:41 AM CST
#  Destription: 监控奇迅的相关句柄数是否正常，每2秒输出一次相关内容
#
################################################################################
cd `dirname $0`

keyInfo="/opt/soft/proxy_server_ng/sbin/proxy_server_ng"
proc_num=""   # 获取到的最新进程id
sleep_idle=2   # 监控间隔

startTime=0

# 获取进程的启动时间
function GetProcStartTime() 
{ 
    local PID=$1
    if [ -z ${PID} ]
    then
        echo "usage ${0} pid"
        return 0    
    fi
    local STARTTIME=$(awk '{print int($22 /100)}' /proc/$PID/stat)
    local UT=$(awk '{print int($1)}' /proc/uptime)
    local NOW=$(date +%s)
    startTime=$((NOW - (UT - STARTTIME)))
    echo "proc $PID start at : `date -d @$startTime`"
}

# 获取最新进程的进程id
function GetLatestPid()
{ 
    proc_num_all=(`ps -ef |grep "${keyInfo}" |grep -v grep |awk '{print $2,$8}' |grep "${keyInfo}" |awk '{print $1}'`)
    proc_num=${proc_num_all[@]}
    for tmpPid in "${proc_num_all[@]}"
    do
        oldTime=${startTime}
        GetProcStartTime ${tmpPid}
        if [ ${oldTime} -lt ${startTime} ]
        then
            proc_num=${tmpPid}
        fi
    done
}

GetLatestPid

while true
do
    sleep ${sleep_idle}
    if [ ! -d /proc/${proc_num} ]
    then
        echo "proc ${proc_num} is dead"
    else 
        proInfo=`ls /proc/${proc_num}/fd -l 2>&1 |awk '
        BEGIN {sum=0; sock=0; efd=0; ep=0; fd=0;} 
        { 
            sum += 1; 
            if($0~"socket") { sock+=1; } 
            else if($0~"eventfd") { efd+=1; } 
            else if($0~"eventpoll") { ep+=1; } 
            else { fd+=1; }
        }
        END {print "total_fd="sum, "sock_num="sock, "eventfd_num="efd, "eventpool_num="ep, "file_fd="fd }'
        `
        vmInfo=`cat /proc/${proc_num}/status |awk 'BEGIN{vm=""; rss="";} { if($0~"VmSize") vm=$2$3 fi; if($0~"VmRSS") rss=$2$3 fi;} END {print "VmSize="vm, "VmRSS="rss}'`
        echo "`date "+%Y-%m-%d %T"` pid=${proc_num} ${proInfo} ${vmInfo}"
    fi
done
exit 0


